package org.systemsbiology.rface.hadoop.data;

import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: anorberg
 * Date: 9/16/11
 * Time: 11:32 AM
 * To change this template use File | Settings | File Templates.
 */
public class UnorderedNamePair implements WritableComparable<UnorderedNamePair> {

    private String key1, key2;
    private static final int MAGIC_SIGNATURE_OPEN = 0xC0FFEEEE;
    private static final int MAGIC_SIGNATURE_CLOSE = 0xABABECAB;

    public UnorderedNamePair(){
        key1 = key2 = null;
    }

    public UnorderedNamePair(String x, String y){
        if(x.compareTo(y) < 0){
            key1 = x;
            key2 = y;
        } else {
            key1 = y;
            key2 = x;
        }
    }

    public int compareTo(UnorderedNamePair o) {
        int x = key1.compareTo(o.key1);
        if(x != 0) return x;
        x = key2.compareTo(o.key2);
        return x;
    }

    public boolean equals(Object o){
        if(o == null) return false;
        if(! o.getClass().equals(this.getClass())) return false;
        UnorderedNamePair foo = (UnorderedNamePair) o;
        return foo.compareTo(this) == 0; //compareTo does strict equality for this class
    }

    public int hashCode(){
        return key1.hashCode() ^ key2.hashCode();
    }

    //DATA FORMAT: OPEN utf8 utf8 CLOSE
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeInt(MAGIC_SIGNATURE_OPEN);
        dataOutput.writeUTF(key1);
        dataOutput.writeUTF(key2);
        dataOutput.writeInt(MAGIC_SIGNATURE_CLOSE);
    }

    public void readFields(DataInput dataInput) throws IOException {
        if(dataInput.readInt() != MAGIC_SIGNATURE_OPEN){
            throw new IOException("Invalid data- open signature mismatch");
        }
        key1 = dataInput.readUTF();
        key2 = dataInput.readUTF();
        if(dataInput.readInt() != MAGIC_SIGNATURE_CLOSE){
            throw new IOException("Invalid data- close signature mismatch");
        }
    }

    public String getKey1(){
        return key1;
    }

    public String getKey2(){
        return key2;
    }

    public String toString(){
        return "<" + key1 + ", " + key2 + ">";
    }
}
